<?php

namespace app\admin\controller\yungift;

use addons\yungift\model\Group;
use app\admin\model\yungift\Activity as ActivityModel;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 活动模块
 */
class Activity extends Backend
{
    /**
     * @var ActivityModel
     */
    protected $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ActivityModel();

        // 活动状态
        $this->view->assign('statusList', $this->model::getStatusList());
        $this->assignconfig('statusList', $this->model::getStatusList());

        // 登录方式
        $this->view->assign('loginMethods', [
            'name_code'     => ['name' => '姓名登录码', 'tip' => '姓名+登录码方式，登录码需要提前生成好'],
            'number_code'   => ['name' => '编号登录码', 'tip' => '编号+登录码方式，登录码需要提前生成好'],
            'phone_captcha' => ['name' => '手机验证码', 'tip' => '手机+验证码方式，手机号必须唯一，必须配置阿里云短信'],
            'wechat_phone'  => ['name' => '微信快捷验证', 'tip' => '手机+验证码方式，手机号必须唯一，可以不用配置阿里云短信']
        ]);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            // 转发到selectPage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            // 重载查询条件
            $filter = $this->request->get('filter');
            $op = $this->request->get('op');
            list($filter, $op) = $this->formatFilterOp($filter, $op);
            $this->request->get(['filter' => $filter, 'op' => $op]);

            // 通用查询条件
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model->where($where)->order($sort, $order)->limit($offset, $limit)->paginate($limit);
            $result = array(
                'total' => $list->total(),
                'rows'  => $list->items(),
            );

            return json($result);
        }

        // 分组列表
        $groupList = Group::getTreeList();
        $groupMap = ['0' => '未分组'];
        foreach ($groupList as $item) {
            $groupMap[$item['id']] = $item['name'];
        }
        $this->view->assign('groupMap', $groupMap);
        $this->assignconfig('groupMap', $groupMap);

        // 是否激活
        $this->view->assign('defaultList', $this->model::getDefaultList());
        $this->assignconfig('defaultList', $this->model::getDefaultList());

        return $this->view->fetch();
    }

    /**
     * 格式化查询条件
     *
     * @param $filter
     * @param $op
     * @return array
     */
    private function formatFilterOp($filter, $op)
    {
        $filter = json_decode($filter, true);
        $op = json_decode($op, true);
        if (array_key_exists('groupId', $filter)) {
            if ($filter['groupId']) {
                $filter['group_ids'] = Group::getRelationIds($filter['groupId']);
            } else {
                $filter['group_ids'] = 0;
            }
            $op['group_ids'] = 'find_in_set';
            unset($filter['groupId'], $op['groupId']);
        }

        return [json_encode($filter), json_encode($op)];
    }

    /**
     * 添加
     */
    public function add()
    {
        if (! $this->request->isPost()) {
            $this->assignconfig('groupTreeList', Group::getTreeSelect());
        } else {
            $params = $this->request->post("row/a");
            if (isset($params['login_methods'])) {
                $params['login_methods'] = implode(',', $params['login_methods']);
            }
            $this->request->post(['row' => $params]);
        }

        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model::get($ids);
        if (! $row) {
            $this->error(__('No Results were found'));
        }

        if (! $this->request->isPost()) {
            $groupIds = $row->group_ids ? explode(',', $row->group_ids) : [];
            $this->assignconfig('groupTreeList', Group::getTreeSelect($groupIds));
        } else {
            $params = $this->request->post("row/a");
            if (isset($params['login_methods'])) {
                $params['login_methods'] = implode(',', $params['login_methods']);
            }
            $this->request->post(['row' => $params]);
        }

        return parent::edit($ids);
    }

    /**
     * 默认
     */
    public function default($ids)
    {
        if (! $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        $action = $this->request->get('action');
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            Db::startTrans();
            try {
                if ($action === 'cancel') {
                    $this->model->where($pk, 'in', $ids)->update(['is_default' => 0]);
                } else {
                    $this->model->where($pk, 'in', $ids)->update(['is_default' => 1]);
                    $this->model->where($pk, 'not in', $ids)->update(['is_default' => 0]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
